package com.ruoyi.business.controller;

import com.alibaba.fastjson.JSON;
import com.ruoyi.business.domain.RackEquipment;
import com.ruoyi.business.service.IRackEquipmentService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 台架设备Controller
 * 
 * @author qiancheng
 * @date 2025-06-13
 */
@Api(tags = "台架设备管理")
@RestController
@RequestMapping("/business/equipment")
public class RackEquipmentController extends BaseController
{
    @Autowired
    private IRackEquipmentService rackEquipmentService;

    @Value("${file.upload.path:/upload}")
    private String uploadPath;

    private static final int MAX_FILE_SIZE_MB = 30;

    /**
     * 实验平台管理->>台架维护管理->>查询台架设备列表
     */
    @ApiOperation("查询台架设备列表")
    @Anonymous
    @GetMapping("/list")
    public TableDataInfo list(@ApiParam("台架设备查询条件") RackEquipment rackEquipment)
    {
        startPage();
        List<RackEquipment> list = rackEquipmentService.selectRackEquipmentList(rackEquipment);
        return getDataTable(list);
    }

    /**
     * 导出台架设备列表
     */
    @ApiOperation("导出台架设备列表")
    @Anonymous
    @PostMapping("/export")
    public void export(HttpServletResponse response, @ApiParam("台架设备查询条件") RackEquipment rackEquipment)
    {
        List<RackEquipment> list = rackEquipmentService.selectRackEquipmentList(rackEquipment);
        ExcelUtil<RackEquipment> util = new ExcelUtil<RackEquipment>(RackEquipment.class);
        util.exportExcel(response, list, "台架设备数据");
    }

    /**
     * 获取台架设备详细信息
     */
    @Anonymous
    @GetMapping(value = "/getRackEquipmentById")
    public AjaxResult getInfo(@RequestParam("id")Long id)
    {
        return success(rackEquipmentService.selectRackEquipmentById(id));
    }

    /**
     * 获取台架设备详细信息
     */
    @Anonymous
    @GetMapping(value = "/getRackEquById")
    public AjaxResult getRackEquById(@RequestParam("id")Long id)
    {
        return success(rackEquipmentService.selectRackEquById(id));
    }


    /**
     * 实验平台管理->>台架维护管理->>新增台架设备
     */
    @ApiOperation("新增台架设备")
    @RepeatSubmit
    @Anonymous
    @PostMapping
    public AjaxResult add(@ApiParam("文件列表") @RequestParam(value = "files", required = false) MultipartFile[] files,
                         @ApiParam("台架设备信息") @RequestParam("rackEquipment") String rackEquipment) {
        try {
            // 将JSON字符串转换为RackEquipment对象
            RackEquipment rackEq = JSON.parseObject(rackEquipment, RackEquipment.class);
            
            // 处理多个文件上传，用逗号分隔文件名
            if (files != null && files.length > 0) {
                List<String> uploadedFileNames = new ArrayList<>();
                
                for (MultipartFile file : files) {
                    if (file != null && !file.isEmpty()) {
                        // 检查文件大小
                        if (file.getSize() > MAX_FILE_SIZE_MB * 1024 * 1024) {
                            return error("文件 " + file.getOriginalFilename() + " 大小不能超过30MB");
                        }
                        
                        try {
                            // 获取文件名
                            String fileName = file.getOriginalFilename();
                            // 生成新的文件名（时间戳+原文件名）
                            String newFileName = System.currentTimeMillis() + "_" + fileName;
                            
                            // 确保上传目录存在
                            File uploadDir = new File(uploadPath);
                            if (!uploadDir.exists()) {
                                uploadDir.mkdirs();
                            }
                            
                            // 构建完整的文件路径
                            File dest = new File(uploadPath + File.separator + newFileName);
                            
                            // 保存文件
                            file.transferTo(dest);
                            uploadedFileNames.add(newFileName);
                            
                            // 添加小延时避免文件名冲突
                            Thread.sleep(1);
                            
                        } catch (Exception e) {
                            return error("文件 " + file.getOriginalFilename() + " 上传失败：" + e.getMessage());
                        }
                    }
                }
                
                // 将上传成功的文件名用逗号连接
                if (!uploadedFileNames.isEmpty()) {
                    rackEq.setDraw(String.join(",", uploadedFileNames));
                }
            }
            
            // 传递null作为文件参数，因为文件已经在Controller层处理了
            return success(rackEquipmentService.insertRackEquipment(null, rackEq));
        } catch (Exception e) {
            return error("新增台架设备失败：" + e.getMessage());
        }
    }

    /**
     * 实验平台管理->>台架维护管理->>修改台架设备
     */
    @ApiOperation("修改台架设备")
    @Anonymous
    @PutMapping
    public AjaxResult edit(@ApiParam("台架设备信息") @RequestBody RackEquipment rackEquipment)
    {
        return toAjax(rackEquipmentService.updateRackEquipment(rackEquipment));
    }

    /**
     * 实验平台管理->>台架维护管理->>删除台架设备
     */
    @ApiOperation("删除台架设备")
    @Anonymous
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@ApiParam("设备ID数组") @PathVariable Long[] ids)
    {
        return toAjax(rackEquipmentService.deleteRackEquipmentByIds(ids));
    }

    /**
     * 文件上传接口（单文件）
     */
    @ApiOperation("文件上传接口（单文件）")
    @Anonymous
    @PostMapping("/upload")
    public AjaxResult uploadFile(@ApiParam("文件") @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return error("上传文件不能为空");
        }
        
        // 检查文件大小
        if (file.getSize() > MAX_FILE_SIZE_MB * 1024 * 1024) {
            return error("文件大小不能超过30MB");
        }
        
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            // 生成新的文件名（时间戳+原文件名）
            String newFileName = System.currentTimeMillis() + "_" + fileName;
            
            // 确保上传目录存在
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 构建完整的文件路径
            File dest = new File(uploadPath + File.separator + newFileName);
            
            // 保存文件
            file.transferTo(dest);
            
            return success("文件上传成功:"+newFileName);
        } catch (IOException e) {
            return error("文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 多文件上传接口
     */
    @ApiOperation("多文件上传接口")
    @Anonymous
    @PostMapping("/upload/multiple")
    public AjaxResult uploadMultipleFiles(@ApiParam("文件列表") @RequestParam("files") MultipartFile[] files) {
        if (files == null || files.length == 0) {
            return error("上传文件不能为空");
        }
        
        List<String> uploadedFiles = new ArrayList<>();
        List<String> failedFiles = new ArrayList<>();
        
        for (MultipartFile file : files) {
            if (file.isEmpty()) {
                failedFiles.add("空文件");
                continue;
            }
            
            // 检查文件大小
            if (file.getSize() > MAX_FILE_SIZE_MB * 1024 * 1024) {
                failedFiles.add(file.getOriginalFilename() + "（文件过大）");
                continue;
            }
            
            try {
                // 获取文件名
                String fileName = file.getOriginalFilename();
                // 生成新的文件名（时间戳+原文件名）
                String newFileName = System.currentTimeMillis() + "_" + fileName;
                
                // 确保上传目录存在
                File uploadDir = new File(uploadPath);
                if (!uploadDir.exists()) {
                    uploadDir.mkdirs();
                }
                
                // 构建完整的文件路径
                File dest = new File(uploadPath + File.separator + newFileName);
                
                // 保存文件
                file.transferTo(dest);
                uploadedFiles.add(newFileName);
                
                // 添加小延时避免文件名冲突
                Thread.sleep(1);
                
            } catch (Exception e) {
                failedFiles.add(file.getOriginalFilename() + "（" + e.getMessage() + "）");
            }
        }
        
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("uploadedFiles", uploadedFiles);
        result.put("failedFiles", failedFiles);
        result.put("totalCount", files.length);
        result.put("successCount", uploadedFiles.size());
        result.put("failedCount", failedFiles.size());
        
        if (failedFiles.isEmpty()) {
            return success(result);
        } else if (uploadedFiles.isEmpty()) {
            return error("所有文件上传失败");
        } else {
            return success(result);
        }
    }

    /**
     * 文件下载接口（支持单文件和多文件下载）
     */
    @ApiOperation("文件下载接口（支持单文件和多文件下载）")
    @Anonymous
    @GetMapping("/download")
    public void downloadFile(@ApiParam("文件名，多个文件用逗号分隔") @RequestParam String fileName, HttpServletResponse response) {
        try {
            // 检查是否为多文件下载（包含逗号）
            if (fileName.contains(",")) {
                downloadMultipleFiles(fileName, response);
            } else {
                downloadSingleFile(fileName, response);
            }
        } catch (Exception e) {
            throw new RuntimeException("文件下载失败：" + e.getMessage());
        }
    }

    /**
     * 下载单个文件
     */
    private void downloadSingleFile(String fileName, HttpServletResponse response) throws Exception {
        // 构建文件路径
        File file = new File(uploadPath + File.separator + fileName);
        
        if (!file.exists()) {
            throw new RuntimeException("文件不存在：" + fileName);
        }
        
        // 获取原始文件名（去掉时间戳前缀）
        String originalFileName = fileName.substring(fileName.indexOf("_") + 1);
        
        // 设置响应头
        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        // 对文件名进行URL编码
        String encodedFileName = java.net.URLEncoder.encode(originalFileName, "UTF-8")
            .replaceAll("\\+", "%20");  // 将+号替换为%20
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodedFileName);
        
        // 读取文件并写入响应
        try (java.io.FileInputStream fis = new java.io.FileInputStream(file);
             java.io.OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        }
    }

    /**
     * 下载多个文件（打包成ZIP）
     */
    private void downloadMultipleFiles(String fileNames, HttpServletResponse response) throws Exception {
        String[] fileNameArray = fileNames.split(",");
        List<File> existingFiles = new ArrayList<>();
        List<String> originalFileNames = new ArrayList<>();
        
        // 检查所有文件是否存在
        for (String fileName : fileNameArray) {
            fileName = fileName.trim();
            if (!fileName.isEmpty()) {
                File file = new File(uploadPath + File.separator + fileName);
                if (file.exists()) {
                    existingFiles.add(file);
                    // 获取原始文件名（去掉时间戳前缀）
                    String originalFileName = fileName.substring(fileName.indexOf("_") + 1);
                    originalFileNames.add(originalFileName);
                }
            }
        }
        
        if (existingFiles.isEmpty()) {
            throw new RuntimeException("没有找到任何有效的文件");
        }
        
        // 设置ZIP文件的响应头
        response.setContentType("application/zip");
        response.setCharacterEncoding("utf-8");
        String zipFileName = "files_" + System.currentTimeMillis() + ".zip";
        String encodedZipFileName = java.net.URLEncoder.encode(zipFileName, "UTF-8")
            .replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + encodedZipFileName);
        
        // 创建ZIP输出流
        try (ZipOutputStream zos = new ZipOutputStream(response.getOutputStream())) {
            byte[] buffer = new byte[1024];
            
            for (int i = 0; i < existingFiles.size(); i++) {
                File file = existingFiles.get(i);
                String originalFileName = originalFileNames.get(i);
                
                // 创建ZIP条目
                ZipEntry zipEntry = new ZipEntry(originalFileName);
                zos.putNextEntry(zipEntry);
                
                // 读取文件并写入ZIP
                try (java.io.FileInputStream fis = new java.io.FileInputStream(file)) {
                    int len;
                    while ((len = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, len);
                    }
                }
                
                zos.closeEntry();
            }
            
            zos.finish();
            zos.flush();
        }
    }

    /**
     * 根据台架ID查询设备列表
     */
    @ApiOperation("根据台架ID查询设备列表")
    @Anonymous
    @GetMapping("/rack/{rackId}")
    public AjaxResult getEquipmentsByRackId(@ApiParam("台架ID") @PathVariable("rackId") Long rackId)
    {
        List<RackEquipment> list = rackEquipmentService.selectRackEquipmentByRackId(rackId);
        return success(list);
    }

    /**
     * 根据台架ID删除所有设备
     */
    @ApiOperation("根据台架ID删除所有设备")
    @Anonymous
    @DeleteMapping("/rack/{rackId}")
    public AjaxResult removeByRackId(@ApiParam("台架ID") @PathVariable("rackId") Long rackId)
    {
        return toAjax(rackEquipmentService.deleteRackEquipmentByRackId(rackId));
    }

    @ApiOperation("文件预览")
    @Anonymous
    @GetMapping("/preview")
    public void previewFile(@RequestParam String fileName, HttpServletResponse response) {
        File file = new File(uploadPath + File.separator + fileName);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在：" + fileName);
        }

        // 获取文件扩展名
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();

        // 根据扩展名设置 Content-Type
        String contentType;
        switch (ext) {
            case "jpg":
            case "jpeg":
            case "png":
            case "gif":
            case "bmp":
                contentType = "image/" + (ext.equals("jpg") ? "jpeg" : ext);
                break;
            case "pdf":
                contentType = "application/pdf";
                break;
            case "txt":
                contentType = "text/plain";
                break;
            case "doc":
            case "docx":
                contentType = "application/msword";
                break;
            case "xls":
            case "xlsx":
                contentType = "application/vnd.ms-excel";
                break;
            default:
                // 其他类型：通用二进制流（浏览器大概率会下载）
                contentType = "application/octet-stream";
        }

        response.setContentType(contentType);
        response.setCharacterEncoding("utf-8");

        try (FileInputStream fis = new FileInputStream(file);
             OutputStream os = response.getOutputStream()) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            os.flush();
        } catch (IOException e) {
            throw new RuntimeException("文件预览失败：" + e.getMessage());
        }
    }

}
